﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SmartSiteManagementSystem.AdminWeb.Common;
using SmartSiteManagementSystem.AdminWeb.Extensions;
using SmartSiteManagementSystem.AdminWeb.Filter;
using SmartSiteManagementSystem.AdminWeb.Models;
using SmartSiteManagementSystem.IServices;
using SmartSiteManagementSystem.Models.Admin;
using SmartSiteManagementSystem.Models.DTO;

namespace SmartSiteManagementSystem.AdminWeb.Controllers
{


    public class HomeController : AdminBaseControllers
    {

        private readonly ILogger<HomeController> _logger;
        private readonly IWebHostEnvironment _webHostEnvironment;

        //注入后台服务
        private readonly IAdminService _adminService;
        public HomeController(IAdminService adminService,IWebHostEnvironment webHostEnvironment, ILogger<HomeController> logger) : base(adminService)
        {
            _logger = logger;
            _adminService = adminService;
            _webHostEnvironment = webHostEnvironment;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [SkipFilterAttribute]
        public IActionResult Index()
        {
            #region 验证是否已登录

            AdminUserInfo AdminObj = HttpContext.Session.Get<AdminUserInfo>(SessionCookieKeyHelper.SessionKey);
            if (AdminObj == null)
            {
                return RedirectToAction("Index", "Login");
            }

            #endregion 验证是否已登录

            //加载样式
            ViewBag.BodyClass = "easyui-layout";
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult Info()
        {
            string remoteIpAddress = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            if (Request.Headers.ContainsKey("X-Forwarded-For"))
                remoteIpAddress = Request.Headers["X-Forwarded-For"];
            ViewBag.remoteIpAddress = remoteIpAddress;

            var userHostAddress = "";
            //HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(userHostAddress))
            {
                userHostAddress = HttpContext.Connection.RemoteIpAddress.ToString();
            }

            ViewBag.userHostAddress = userHostAddress;

            //最后判断获取是否成功，并检查IP地址的格式（检查其格式非常重要）
            //if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
            //{
            //    return userHostAddress;
            //}

            return View();
        }

        /// <summary>
        /// 检查IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        private bool IsIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        /// <summary>
        /// 获取左侧菜单数据
        /// </summary>
        [SkipFilterAttribute]
        public JsonResult GetLeft()
        {
            IList<Hashtable> back = new List<Hashtable>();
            AdminUserInfo AdminObj = HttpContext.Session.Get<AdminUserInfo>(SessionCookieKeyHelper.SessionKey);
            if (AdminObj != null)
            {
                IList<AdminMenuInfo> MenuList = _adminService.GetNavigationMenu(AdminObj.AdminUserId, AdminObj.UserType);
                back = _adminService.GetTree(MenuList);
            }
            return Json(back);
        }



        /// <summary>
        /// 没有权限提示页
        /// </summary>
        /// <returns></returns>
        [SkipFilterAttribute]
        public ActionResult noRight()
        {
            return View();
        }

        [SkipFilterAttribute]
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }


        [SkipFilterAttribute]
        public ActionResult UploadFile0()
        {

            return View();
        }

        [SkipFilter]
        public string ChangeLink(string thirdLink)
        {
            string newFileName = "";
                //Uploader.UploadImgByWebServiceFromURL(thirdLink);
            return newFileName;
        }


        [SkipFilter]
        public JsonResult UploadImgByWebService()
        {

            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 0;
            result.Msg = "操作失败!";
            //bool createThumbnail = false;
            Int32 fileSizeLimit = 10 * 1024;

            #region 设置禁用缓存
            /*
            设置禁用缓存
           <meta http-equiv="pragram" content="no-cache">  
           <meta http-equiv="cache-control" content="no-cache, must-revalidate"> 
           <meta http-equiv="expires" content="0">
            */
            Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.CacheControl] = "no-cache,must-revalidate";
            Response.Headers["Pragma"] = "no-cache";
            Response.Headers["expires"] = "0";
            #endregion

            try
            {

                IFormFile jpeg_image_upload = HttpContext.Request.Form.Files[0];
                var fileSize = jpeg_image_upload.Length;
                if (fileSize > 1024 * fileSizeLimit)
                {
                    result.IsSuccess = false;
                    HttpContext.Response.StatusCode = 200;
                    result.Msg = "图片的文件大小不能大于10M";

                }
                else
                {
                    DateTime n = DateTime.Now;
                    string guid = Guid.NewGuid().ToString();
                    var webRootPath = _webHostEnvironment.WebRootPath;//获取项目路径
                    string newFileName = guid + "_" + Path.GetExtension(jpeg_image_upload.FileName);
                    // MImageConfig.FileRootDir
                    string filePath = "/UploadFileRoot/";
                    string fullFileName= webRootPath + filePath+ newFileName;
                   
                    string exn = Path.GetExtension(jpeg_image_upload.FileName).ToLower();

                    if (exn != ".jpg" && exn != ".jpeg" && exn != ".bmp" && exn != ".gif" && exn != ".png")
                    {
                        HttpContext.Response.StatusCode = 200;
                        result.Msg =  "请使用jpg、jpeg、bmp、gif、png格式的图片";
                    }
                    else
                    {

                        if (!Directory.Exists(webRootPath + filePath))
                        {
                            Directory.CreateDirectory(webRootPath + filePath);
                        }
                        if (jpeg_image_upload != null)
                        {


                            //文件保存
                            using (var fs = System.IO.File.Create(fullFileName))
                            {
                                jpeg_image_upload.CopyTo(fs);
                                fs.Flush();
                            }
                            //完整的文件路径
                            var completeFilePath = Path.Combine(filePath, newFileName);
                            result.IsSuccess = true;
                            result.Code = 1;
                            result.Msg = completeFilePath.ToString();
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message.ToString());
                result.Msg = "err:" + ex.Message;
            }
            return Json(result);
        }
    }
}
